package com.lej.core.widget.scrollNum

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import com.lej.core.R
import java.util.*

class DanceNumberView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private var text: String? = null
    private var textColor = 0
    private var textSize = 16f
    private var textPadding = 0 //文字间距
    private val list: MutableList<SingleScrollNumberView> = ArrayList()

    private fun createView() {
        removeAllViews()
        list.clear()
        text?.toCharArray()?.forEach {
            val scrollNumber = SingleScrollNumberView(context)
                .setTextColor(textColor)
                .setTextSize(textSize)
                .setTextPadding(textPadding)
                .setText(it)
            addView(scrollNumber)
            list.add(scrollNumber)
        }
    }

    private fun startAnimation() {
        list.forEach { it.start() }
    }

    private fun initAttributesData(typedArray: TypedArray) {
        textColor = typedArray.getColor(R.styleable.DanceNumberView_textColor, Color.BLACK)
        textSize = typedArray.getDimension(R.styleable.DanceNumberView_textSize, textSize)
        text = typedArray.getString(R.styleable.DanceNumberView_text)
        textPadding = typedArray.getDimension(
            R.styleable.DanceNumberView_textPadding,
            textPadding.toFloat()
        ).toInt()
    }

    fun setContent(content: String?) {
        text = content
        createView()
        startAnimation()
    }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.DanceNumberView)
        initAttributesData(typedArray)
        this.orientation = HORIZONTAL
        this.gravity = Gravity.CENTER
    }
}